package ZuoYe.I;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * 转账界面
 */
public class TransferPanel extends JPanel implements ActionListener {
    private ATMFrame atmFrame;
    private JLabel accountJLabel = new JLabel("转账账号：");
    private JLabel moneyJLabel= new JLabel("转账金额：");
    private JTextField accountField = new JTextField();
    private JTextField moneyField = new JTextField();
    private ImageIcon sureImg= new ImageIcon("picture/buttonSure.jpg");
    private ImageIcon clearImg= new ImageIcon("picture/buttonClear.jpg");
    private Font font = new Font("黑体",Font.BOLD,20);
    private JButton sureBth= new JButton(sureImg);
    private JButton clearBth= new JButton(clearImg);
    public TransferPanel(ATMFrame atmFrame){
        this.atmFrame = atmFrame;
        this.setLayout(null);
        accountJLabel.setBounds(200,200,250,50);
        accountJLabel.setFont(font);
        accountField.setBounds(400,200,250,50);
        accountField.setFont(font);
        moneyJLabel.setBounds(200,300,250,50);
        moneyJLabel.setFont(font);
        moneyField.setBounds(400,300,250,50);
        moneyField.setFont(font);
        sureBth.setBounds(530,370,140,50);
        sureBth.addActionListener(this);
        clearBth.setBounds(360,370,150,50);
        this.add(accountField);
        this.add(accountJLabel);
        this.add(moneyField);
        this.add(moneyJLabel);
        this.add(sureBth);
        this.add(clearBth);
        this.setOpaque(false);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource()==sureBth){
            List users = atmFrame.getUsers();
            User user = atmFrame.getLoginUser();
                if (Double.parseDouble(moneyField.getText()) > user.getBlance()){
                    JOptionPane.showMessageDialog(this,"您的余额不足");
                    return;
                }
                if (accountField.getText().equals(user.getAccount())){
                    JOptionPane.showMessageDialog(this,"不能转给自己");
                    return;
                }

                for (int i = 0;i < users.size();i++){
                    User u = (User) users.get(i);
                    if (accountField.getText().equals(u.getAccount())){
                       u.setBlance(u.getBlance()+Double.parseDouble(moneyField.getText()));
                       user.setBlance(user.getBlance()-Double.parseDouble(moneyField.getText()));
                        JOptionPane.showMessageDialog(this,"转账成功");
                       atmFrame.switchPanel("menu");
                       return;
                    }
                }
                JOptionPane.showMessageDialog(this,"输入的账号有误");
                return;
        }
    }
}
